package com.healthai.service;

import com.healthai.dto.request.ChangePasswordRequest;
import com.healthai.dto.request.LoginRequest;
import com.healthai.dto.request.RegisterRequest;
import com.healthai.dto.request.UpdateUserRequest;
import com.healthai.dto.response.LoginResponse;
import com.healthai.dto.response.UserInfoResponse;
import com.healthai.entity.User;
import com.healthai.exception.BusinessException;
import com.healthai.mapper.UserMapper;
import com.healthai.util.JwtUtil;
import com.healthai.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordUtil passwordUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户注册
     * @param registerRequest 注册请求
     * @return 用户ID
     */
    public Integer register(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(registerRequest.getUsername());
        if (existingUser != null) {
            throw new BusinessException(400, "用户名已存在");
        }
        
        // 检查手机号是否已存在
        if (registerRequest.getPhone() != null) {
            User existingPhoneUser = userMapper.findByPhone(registerRequest.getPhone());
            if (existingPhoneUser != null) {
                throw new BusinessException(400, "手机号已被注册");
            }
        }
        
        // 检查邮箱是否已存在
        if (registerRequest.getEmail() != null) {
            User existingEmailUser = userMapper.findByEmail(registerRequest.getEmail());
            if (existingEmailUser != null) {
                throw new BusinessException(400, "邮箱已被注册");
            }
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordUtil.encode(registerRequest.getPassword()));
        user.setPhone(registerRequest.getPhone());
        user.setEmail(registerRequest.getEmail());
        user.setRealName(registerRequest.getRealName());
        user.setGender(registerRequest.getGender());
        user.setBirthDate(registerRequest.getBirthDate());
        user.setStatus(1);
        
        userMapper.insert(user);
        
        return user.getUserId();
    }
    
    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    public LoginResponse login(LoginRequest loginRequest) {
        // 查找用户
        User user = userMapper.findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new BusinessException(400, "用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordUtil.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new BusinessException(400, "用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException(400, "账号已被禁用");
        }
        
        // 生成JWT令牌
        String token = jwtUtil.generateToken(user.getUsername());
        
        return new LoginResponse(token, user.getUsername(), user.getUserId());
    }
    
    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return 用户信息
     */
    public User getUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    public User getUserById(Integer userId) {
        return userMapper.findById(userId);
    }
    
    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 是否成功
     */
    public boolean updateUser(User user) {
        return userMapper.update(user) > 0;
    }
    
    /**
     * 获取用户信息响应
     * @param username 用户名
     * @return 用户信息响应
     */
    public UserInfoResponse getUserInfo(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        
        UserInfoResponse response = new UserInfoResponse();
        response.setUserId(user.getUserId());
        response.setUsername(user.getUsername());
        response.setPhone(user.getPhone());
        response.setEmail(user.getEmail());
        response.setRealName(user.getRealName());
        response.setGender(user.getGender());
        response.setBirthDate(user.getBirthDate());
        response.setHeight(user.getHeight());
        response.setTargetWeight(user.getTargetWeight());
        response.setHealthGoal(user.getHealthGoal());
        response.setHealthNotes(user.getHealthNotes());
        response.setCreateTime(user.getCreateTime());
        response.setUpdateTime(user.getUpdateTime());
        response.setStatus(user.getStatus());
        
        return response;
    }
    
    /**
     * 更新用户信息
     * @param username 用户名
     * @param updateUserRequest 更新用户信息请求
     * @return 用户信息响应
     */
    public UserInfoResponse updateUserInfo(String username, UpdateUserRequest updateUserRequest) {
        User user = userMapper.findByUsername(username);

        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        
        // 更新用户信息
        if (updateUserRequest.getPhone() != null) {
            // 检查手机号是否已被其他用户使用
            User existingPhoneUser = userMapper.findByPhone(updateUserRequest.getPhone());
            if (existingPhoneUser != null && !existingPhoneUser.getUserId().equals(user.getUserId())) {
                throw new BusinessException(400, "手机号已被其他用户使用");
            }
            user.setPhone(updateUserRequest.getPhone());
        }
        
        if (updateUserRequest.getEmail() != null) {
            // 检查邮箱是否已被其他用户使用
            User existingEmailUser = userMapper.findByEmail(updateUserRequest.getEmail());
            if (existingEmailUser != null && !existingEmailUser.getUserId().equals(user.getUserId())) {
                throw new BusinessException(400, "邮箱已被其他用户使用");
            }
            user.setEmail(updateUserRequest.getEmail());
        }
        
        if (updateUserRequest.getRealName() != null) {
            user.setRealName(updateUserRequest.getRealName());
        }
        
        if (updateUserRequest.getGender() != null) {
            user.setGender(updateUserRequest.getGender());
        }
        
        if (updateUserRequest.getBirthDate() != null) {
            user.setBirthDate(updateUserRequest.getBirthDate());
        }
        
        if (updateUserRequest.getHeight() != null) {
            user.setHeight(updateUserRequest.getHeight());
        }
        
        if (updateUserRequest.getTargetWeight() != null) {
            user.setTargetWeight(updateUserRequest.getTargetWeight());
        }
        
        if (updateUserRequest.getHealthGoal() != null) {
            user.setHealthGoal(updateUserRequest.getHealthGoal());
        }
        
        if (updateUserRequest.getHealthNotes() != null) {
            user.setHealthNotes(updateUserRequest.getHealthNotes());
        }
        
        // 更新数据库
        userMapper.update(user);
        
        // 返回更新后的用户信息
        return getUserInfo(username);
    }
    
    /**
     * 修改密码
     * @param username 用户名
     * @param changePasswordRequest 修改密码请求
     * @return 是否成功
     */
    public boolean changePassword(String username, ChangePasswordRequest changePasswordRequest) {

        
        // 获取用户信息
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        
        // 验证原密码是否正确
        if (!passwordUtil.matches(changePasswordRequest.getOldPassword(), user.getPassword())) {
            throw new BusinessException(400, "原密码不正确");
        }
        
        // 更新密码
        user.setPassword(passwordUtil.encode(changePasswordRequest.getNewPassword()));
        int result = userMapper.update(user);
        
        return result > 0;
    }
}